package com.yuntsg.nnsfcp.util.zhang;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

public class HttpUtil {
    public static String getHtml(CookieStore cookieStore, String url, String referer) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
//        CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
//                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httpget = new HttpGet(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);
                httpget.setConfig(requestConfig);

                httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
                httpget.addHeader(HttpHeaders.REFERER, referer);
                responce = httpClient.execute(httpget);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时"
                        + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static String postHtml(CookieStore cookieStore, String url, String referer, String args) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
//        CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
//                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);
                httppost.setConfig(requestConfig);
                httppost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
                httppost.addHeader(HttpHeaders.REFERER, referer);
                httppost.setEntity(new StringEntity(args));
                responce = httpClient.execute(httppost);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时"
                        + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_MOVED_PERMANENTLY || resStatu == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header header = responce.getFirstHeader("location");
                    String redirectUrl = new URL(new URL(url), header.getValue().replace(" ", "+")).toString();
                    System.out.println("跳转地址" + redirectUrl);
                    html = getHtml(cookieStore, redirectUrl, referer);
                    break;
                } else if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }


    public static void createFile(String path, byte[] content)
            throws IOException {

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

}
